package com.fjp.heartguard.ui.mine

import android.content.Intent
import android.os.Bundle
import coil.load
import coil.transform.RoundedCornersTransformation
import com.fjp.heartguard.R
import com.fjp.heartguard.app.App
import com.fjp.heartguard.app.Constants
import com.fjp.heartguard.app.base.BaseFragment
import com.fjp.heartguard.app.data.bean.AppVersion
import com.fjp.heartguard.app.eventViewModel
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.app.util.AppUtils
import com.fjp.heartguard.app.util.CacheUtil
import com.fjp.heartguard.databinding.FragmentMineBinding
import com.fjp.heartguard.ui.checkversion.CheckVersionActivity
import com.fjp.heartguard.ui.login.LoginActivity
import com.fjp.heartguard.ui.message.MessageActivity
import com.fjp.heartguard.ui.userinfo.UserinfoActivity
import com.fjp.heartguard.viewmodel.MineViewModel
import com.lxj.xpopup.XPopup

import me.hgj.jetpackmvvm.ext.util.dp2px
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.dp2px

class MineFragment : BaseFragment<MineViewModel, FragmentMineBinding>() {
    lateinit var appVersion: AppVersion


    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        mDatabind.click = ClickProxy()
        mViewModel.checkVersion()
        mDatabind.updateMl.setValue("V${AppUtils.getAppVersionName(requireContext())}")
        val days = (System.currentTimeMillis() / 1000 - App.userInfo.created_at) / 60 / 60 / 24
        mDatabind.desTv.text = "加入清心守护的第${days}天"
        mDatabind.nameTv.text = if(App.userInfo.name.isEmpty()) App.userInfo.mobile else App.userInfo.name
        mDatabind.avatarIv.load(App.userInfo.profile, builder = {
            allowHardware(false)
            transformations(RoundedCornersTransformation(requireContext().dp2px(30).toFloat()))
//            this.error(R.drawable.avatar_default)
//            this.placeholder(R.drawable.avatar_default)
        })
        //MainActivity也获取了数量，为了
        mViewModel.getQuestionnaireCount()
//        mDatabind.messageMl.setValue()
        mDatabind.updateMl.setValue("V" + AppUtils.getAppVersionName(requireContext()))
        mDatabind.logoutMl.setOnClickListener {
            showLogoutPop()
        }

//        activity?.let {
//            val picker = AddressPicker(it)
//            picker.setTitle("请选择")
//            picker.okView.setTextColor(Color.BLUE)
//            picker.okView.textSize=30f
//            picker.cancelView.setTextColor(Color.RED)
//            picker.titleView.setTextColor(Color.CYAN)
//            picker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
//            picker.show()
//        }

    }

    override fun createObserver() {
        super.createObserver()
        eventViewModel.unreadMessageEvent.observeInFragment(this) {
            if (it != 0) {
                //如果有新消息的话显示带点的消息图标
                mDatabind.messageMl.setValue(it.toString())
            }else{
                mDatabind.messageMl.setValue("")
            }
        }
        eventViewModel.questionnatireCountEvent.observeInFragment(this) {
            mDatabind.serviceOlderTv.text = it.older_nums.toString()
            mDatabind.checkReportTv.text = it.questionnaire_nums.toString()
        }

        eventViewModel.userInfoChange.observeInFragment(this) {
            mDatabind.nameTv.text = App.userInfo.name
            mDatabind.avatarIv.load(App.userInfo.profile, builder = {
                allowHardware(false)
                transformations(RoundedCornersTransformation(requireContext().dp2px(30).toFloat()))
            })
        }
        mViewModel.questionnatireCount.observe(this) {
            parseState(it, {
                mDatabind.serviceOlderTv.text = it.older_nums.toString()
                mDatabind.checkReportTv.text = it.questionnaire_nums.toString()
            })
        }
        mViewModel.appVersion.observe(this) {
            parseState(it, {
                appVersion = it
                if (appVersion.version != AppUtils.getAppVersionName(requireContext())) {
                    mDatabind.updateMl.setValue("有新版本请及时更新")
                }
            })
        }
    }

    inner class ClickProxy {
        fun clickCheckAppVersion() {
            if (appVersion.version != AppUtils.getAppVersionName(requireContext())) {
                val intent = Intent(context, CheckVersionActivity::class.java)
                intent.putExtra(Constants.INTENT_APP_VERISON, appVersion)
                startActivity(intent)
            } else {
                appContext.showToast("当前已经是最新版本")
            }
        }

        fun clickLogout() {
            showLogoutPop()
        }

        fun clickMessageList() {
            startActivity(Intent(context, MessageActivity::class.java))
        }

        fun clickUserInfo() {
            startActivity(Intent(context, UserinfoActivity::class.java))
        }
        fun clickHelp() {
            startActivity(Intent(context, HelpActivity::class.java))
        }
    }

    private fun showLogoutPop() {
        XPopup.Builder(context).asConfirm("退出登录", "确定退出登录吗？", "取消", "确定", {
            CacheUtil.setUser(null)
            eventViewModel.exitApp.postValue(true)
            startActivity(Intent(context,LoginActivity::class.java))
        }, {}, false).show()
    }
}